// JavaScript Document
$(function() {
    /*显示html*/
    var text = $('#content').text();
    $('#content').html(text);

    /*实时监听评价textarea的文本数量以及限制数量*/
    $('#comment_textarea').on('input propertychange', function() {
        var charNum = $(this).val().length;
        if(charNum > 1000) {
            $('#char_num').html(1000);
            $(this).val($(this).val().substring(0, 1000));
            alert('字符数不能超过1000');
        }else{
            $('#char_num').html(charNum);
        }
    })

    /*点击定位到评价列表*/
    $('#comment_num').on('click', function() {
        $('body,html').animate({scrollTop: $('#comments_panel').offset().top}, 300);
    })
})

$(function() {

    updateCommentList();

    function updateCommentList() {
        $.ajax({
            url: '/article/comment/list',
            type: 'POST',
            data: {
                'art_id' : $('#article_Id').val()
            },
            success: function(data) {
                console.log(data);
                var data = data.data;
                var commentHtml = '';
                if(data == '' || data == null){
                    return;
                }else{
                    var length = data.length;
                    for(var i = 0;i < data.length; i++){
                        commentHtml += '<ul class="comment_item">';
                        commentHtml += '<li><input type="hidden" value="' + data[i].id + '" /></li>';
                        commentHtml += '<li class="comment_img"><a href="#"><img src="' + data[i].URL + '" width="55" height="55" />';
                        commentHtml += '<div class="comments_nickname">' + data[i].nickname + '</div></a><input type="hidden" value="' + data[i].comment_name + '" /></li>';
                        commentHtml += '<li class="comment_body">';
                        commentHtml += '<div class="comment_time">' + getDateDiff(data[i].comment_time) +  '</div>';
                        commentHtml += '<div class="comment_content">' + data[i].comment_content + '</div>';
                        commentHtml += '<ul class="comment_options">';
                        commentHtml += '<li class="left">#' + length-- + '楼</li><li class="praise" style="color:'+ ((data[i].isPraise!=0)?"#369":"#c2c2c2") + '"><i class="glyphicon glyphicon-thumbs-up"></i>&nbsp;<span>' + ((data[i].praise_num==0)?"":data[i].praise_num) + '</span></li>';
                        if(data[i].reply_num > 0)
                            commentHtml += '<li class="look_reply">查看回复</li>';
                        else
                            commentHtml += '<li class="look_reply" style="display: none;">查看回复</li>';
                        commentHtml += '<li class="reply">回复</li>';
                        if(data[i].status == 1)
                            commentHtml += '<li class="del">删除</li>';
                        commentHtml += '</ul></li>';
                        commentHtml += '<div class="reply_dialog_panel">';
                        commentHtml += '<textarea class="reply_textarea pull-left" placeholder="回复&nbsp;' + data[i].nickname + '&nbsp;："></textarea>';
                        commentHtml += '<input type="button" class="btn btn-success btn-sm pull-right" value="回复" /><span class="clearfix"></span>';
                        commentHtml += '</div>';
                        commentHtml += '<div class="reply_list_panel" id="reply_list"></div>';
                        commentHtml += '</ul>';
                    }
                    $('#comments_list').html(commentHtml);
                    getReply1DialogMessage();
                    lookReplyMessage();
                    praiseFun();
                    deleteComment();
                }
            },
            error: function(err) {
                console.log(err);
            }
        });
    }

    /*文章评价*/
    $('#comment_submit').on('click', function() {
        var content = $('#comment_textarea').val();
        if(content.trim() == '' || content == null){
            alert('请输入评价内容');
            return;
        }else{
            content = content.replace(/&/g,'&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
            content = content.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(/\s/g,'&nbsp;');
            $.ajax({
                url: '/user/article/comment/publish',
                type: 'POST',
                data:{
                    "artId": $('#article_Id').val(),
                    "commentContent" : content,
                    "commentTime" : new Date().getTime()
                },
                success: function(data) {
                    data = JSON.parse(data);
                    console.log(data.code);
                    if(data.code==200){
                        $('#comment_textarea').val("");
                        $('#char_num').html(0);
                        layer.msg('评价成功', {time: 2000});
                    }
                    else if(data.code==0)  layer.msg('评价失败', {time: 2000});
                    updateCommentList();
                },
                error: function () {
                    layer.msg('回调失败', {time: 1000});
                }
            });
        }
    })


    /*查看回复和收起回复*/
    function lookReplyMessage() {
        $('.look_reply').each(function(index){
            $(this).on('click', function(){
                var text = $(this).text();
                var replyListPanel = $(this).parents('.comment_item').children('.reply_list_panel');
                if(replyListPanel.is(':hidden')){
                    $.ajax({
                        url: '/article/reply/list',
                        type: 'POST',
                        data: {
                            'comment_id' : $(this).parents('.comment_item').children('li').children('input').val()
                        },
                        success: function(data) {
                            console.log(data);
                            var data = data.data;
                            var replyHtml = '';
                            for(var i = 0;i < data.length;i++){
                                replyHtml += '<ul class="reply_item"><li class="reply_img">';
                                replyHtml += '<a href="#"><img src="' + data[i].reply_from_headurl + '" width="40" height="40" /></a>';
                                replyHtml += '<input type="hidden" value="' + data[i].id + '"/></li>';
                                replyHtml += '<li class="reply_body"><div class="reply_time">' + getDateDiff(data[i].reply_time) + '</div>';
                                replyHtml += '<div class="reply_content">';
                                replyHtml += '<span class="reply_title"><a href="#">' + data[i].reply_from_nickname + '</a>&nbsp;回复&nbsp;<a href="#">' + data[i].reply_to_nickname + '</a>：</span>';
                                replyHtml += '<input type="hidden" value="' + data[i].reply_from_name + '" />';
                                replyHtml += '<span>' + data[i].reply_content + '</span></div>';
                                replyHtml += '<ul class="comment_options">';
                                replyHtml += '<li class="left"></li><li class="reply_praise" style="color:'+ ((data[i].isPraise!=0)?"#369":"#c2c2c2") + '"><i class="glyphicon glyphicon-thumbs-up"></i>&nbsp;<span>' + ((data[i].praise_num==0)?"":data[i].praise_num) + '</span></li>';
                                replyHtml += '<li class="reply2">回复</li>';
                                if(data[i].status == 1)
                                    replyHtml += '<li class="reply_del">删除</a></li>';
                                replyHtml += '</ul></li></ul>';
                            }
                            $(replyListPanel).html(replyHtml);
                            $('body,html').animate({scrollTop: replyListPanel.parents('.comment_item').offset().top}, 300);
                            getReply2DialogMessage();
                            praiseReplyFun();
                            deleteReply();
                        },
                        error: function(err) {
                        }
                    });
                }
                $(this).parents('.comment_item').children('.reply_dialog_panel').hide();
                replyListPanel.toggle();
                $(this).text(text==='查看回复' ? '收起回复' : '查看回复');
            });
        });
    }

    /*获取回复框（评价内回复）信息*/
    function getReply1DialogMessage() {
        $('.reply').each(function(index){
            var el = $(this);
            $(el).on('click', function(){
                /*实时监听回复textarea的文本数量以及限制数量*/
                $(this).parents('.comment_item').children('.reply_dialog_panel').children('textarea').on('input propertychange', function() {
                    var charNum = $(this).val().length;
                    if(charNum > 1000) {
                        $(this).val($(this).val().substring(0, 1000));
                        alert('字符数不能超过1000');
                    }
                })
                var commentItem = $(this).parents('.comment_item');
                var commentId = commentItem.children('li').children('input').val();
                var fromNickname = commentItem.children('.comment_img').children('a').children('.comments_nickname').text();
                var fromUsername = commentItem.children('.comment_img').children('input').val();
                console.log(commentId);
                console.log(fromUsername);
                var replyDialog = commentItem.children('.reply_dialog_panel');
                var replyListPanel = commentItem.children('.reply_list_panel');
                replyDialog.toggle();
                $('body,html').animate({scrollTop: replyDialog.parents('.comment_item').offset().top}, 300);
                replyDialog.children('textarea').val('');
                replyDialog.children('textarea').attr('placeholder', '回复 ' + fromNickname + '：');
                replyDialog.children('input').unbind('click');
                replyDialog.children('input').bind('click', function() {
                    var replyContent = replyDialog.children('textarea').val();
                    requestReplyMessage(commentId, replyContent, new Date().getTime(), fromUsername, replyDialog, replyListPanel);
                    /*改进后可能会报bug*/
                    var lookReply = $(el).parent('.comment_options').children('.look_reply');
                    lookReply.css('display', 'block');
                    lookReply.text('收起回复');
                    replyListPanel.show();
                    /*end*/
                })
            });
        })
    }

    /*获取回复框（回复内回复）信息*/
    function getReply2DialogMessage() {
        $('.reply2').each(function(index) {
            var el = $(this);
            $(el).on('click', function() {
                var commentId = $(this).parents('.comment_item').children('li').children('input').val();
                var fromNickname = $(this).parents('.reply_item').children('.reply_body').children('.reply_content').children('.reply_title').children('a:first-child').text();
                var fromUsername = $(this).parents('.reply_item').children('.reply_body').children('.reply_content').children('input').val();
                console.log(commentId);
                console.log(fromNickname);
                console.log(fromUsername);
                var replyDialog = $(this).parents('.comment_item').children('.reply_dialog_panel');
                var replyListPanel = $(this).parents('.comment_item').children('.reply_list_panel');
                replyDialog.show();
                $('body,html').animate({scrollTop: replyDialog.parents('.comment_item').offset().top}, 300);
                replyDialog.children('textarea').val('');
                replyDialog.children('textarea').attr('placeholder', '回复 ' + fromNickname + '：');
                replyDialog.children('input').unbind('click');
                replyDialog.children('input').bind('click', function() {
                    var replyContent = replyDialog.children('textarea').val();
                    requestReplyMessage(commentId, replyContent, new Date().getTime(), fromUsername, replyDialog, replyListPanel);
                })
            })
        })
    }

    /*请求回复信息*/
    function requestReplyMessage(commentId, replyContent, replyTime, fromUsername, replyDialog, replyList) {
        if(replyContent.trim() == '' || replyContent == null){
            alert('请输入回复的内容');
            return;
        }else{
            replyContent = replyContent.replace(/&/g,'&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
            replyContent = replyContent.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(/\s/g,'&nbsp;');
            $.ajax({
                url: '/user/article/reply/publish',
                type: 'POST',
                data: {
                    "commentId": commentId,
                    "replyComment" : replyContent,
                    "replyTime" : replyTime,
                    "toUsername" : fromUsername
                },
                success: function(data) {
                    data = JSON.parse(data);
                    console.log(data.code);
                    if(data.code==200) layer.msg('回复成功', {time: 2000});
                    else if(data.code==0)  layer.msg('回复失败', {time: 2000});
                    replyDialog.children('textarea').val('');
                    $.ajax({
                        url: '/article/reply/list',
                        type: 'POST',
                        data: {
                            'comment_id' : replyDialog.parents('.comment_item').children('li').children('input').val()
                        },
                        success: function(data) {
                            console.log(data);
                            var data = data.data;
                            var replyHtml = '';
                            for(var i = 0;i < data.length;i++){
                                replyHtml += '<ul class="reply_item"><li class="reply_img">';
                                replyHtml += '<a href="#"><img src="' + data[i].reply_from_headurl + '" width="40" height="40" /></a>';
                                replyHtml += '<input type="hidden" value="' + data[i].id + '"/></li>';
                                replyHtml += '<li class="reply_body"><div class="reply_time">'+ getDateDiff(data[i].reply_time) + '</div>';
                                replyHtml += '<div class="reply_content">';
                                replyHtml += '<span class="reply_title"><a href="#">' + data[i].reply_from_nickname + '</a>&nbsp;回复&nbsp;<a href="#">' + data[i].reply_to_nickname + '</a>：</span>';
                                replyHtml += '<input type="hidden" value="' + data[i].reply_from_name + '" />';
                                replyHtml += '<span>' + data[i].reply_content + '</span></div>';
                                replyHtml += '<ul class="comment_options">';
                                replyHtml += '<li class="left"></li><li class="reply_praise" style="color:'+ ((data[i].isPraise!=0)?"#369":"#c2c2c2") + '"><i class="glyphicon glyphicon-thumbs-up"></i>&nbsp;<span>' + ((data[i].praise_num==0)?"":data[i].praise_num) + '</span></li>';
                                replyHtml += '<li class="reply2">回复</li>';
                                if(data[i].status == 1)
                                    replyHtml += '<li class="reply_del">删除</a></li>';
                                replyHtml += '</ul></li></ul>';
                            }
                            $(replyList).html(replyHtml);
                            getReply2DialogMessage();
                            praiseReplyFun();
                            deleteReply();
                        },
                        error: function(err) {
                            layer.msg('回调函数失败', {time: 2000});
                        }
                    });
                },
                error: function () {
                    layer.msg('回调失败', {time: 1000});
                }
            });
        }
    }

    /**
     * 评价删除权限
     */
    function deleteComment() {
        $('.del').each(function(index) {
            var el = $(this);
            $(this).on('click', function() {
                var commentId = $(this).parents('.comment_item').children('li:first-child').children('input').val();
                layer.confirm('是否删除该评价？',{
                    btn:['确定','取消']
                }, function() {
                    $.ajax({
                        url: '/user/article/comment/delete',
                        type: 'POST',
                        data:{
                            'comment_id': commentId
                        },
                        success: function(data) {
                            data = JSON.parse(data);
                            if(data.code=='200'){
                                el.parents('.comment_item').remove();
                                var size = $('#comments_list .comment_item').length;
                                if(size == 0) {
                                    $('#comments_list').html('<div class="default_background">暂无评价</div>');
                                }else{
                                    $('#comments_list .comment_item').each(function(i) {
                                        $(this).children('.comment_body').children('.comment_options').children('.left').text('#'+size--+'楼');
                                    })
                                }
                                layer.msg("删除成功", {time: 2000});
                            }else{
                                layer.msg("删除失败", {time: 2000});
                            }
                        },
                        error: function(err) {
                            layer.msg("回调函数失败");
                        }
                    });
                }, function() {
                    return;
                });
            })

        })
    }

    /**
     * 回复删除权限
     */
    function deleteReply() {
        $('.reply_del').each(function(index) {
            var el = $(this);
            $(this).on('click', function() {
                var replyId = $(this).parents('.reply_item').children('li:first-child').children('input').val();
                layer.confirm('是否删除该回复？',{
                    btn:['确定','取消']
                }, function() {
                    $.ajax({
                        url: '/user/article/reply/delete',
                        type: 'POST',
                        data:{
                            'reply_id': replyId
                        },
                        success: function(data) {
                            data = JSON.parse(data);
                            if(data.code=='200'){
                                var replyPanel = $(el).parents('#reply_list');
                                el.parents('.reply_item').remove();
                                var size = $('#reply_list .reply_item').size();
                                if(size == 0){
                                    replyPanel.parents('.comment_item').children('.comment_body').children('.comment_options').children('.look_reply').removeAttr('style').css('display', 'none');
                                }
                                layer.msg("删除成功", {time: 2000});
                            }else{
                                layer.msg("删除失败", {time: 2000});
                            }
                        },
                        error: function(err) {
                            layer.msg("回调函数失败");
                        }
                    });
                }, function() {
                    return;
                });
            })
        })
    }


    /**
     * 评价点赞
     */
    function praiseFun() {
        $('.praise').each(function (index) {
            var el = $(this);
            $(this).on('click', function() {
                var commentId = $(this).parents('.comment_item').children('li:first-child').children('input').val();
                $.ajax({
                    url: '/user/article/comment/praise',
                    type: 'POST',
                    data:{
                        'comment_id': commentId
                    },
                    success: function(data) {
                        data = JSON.parse(data);
                        console.log(data.message);
                        if(data.code=='200'){
                            if(data.message > 0){
                                $(el).css('color', '#369');
                                var praiseNum = $(el).children('span').text();
                                if(praiseNum == '' || praiseNum == null) praiseNum = 0;
                                $(el).children('span').text(++praiseNum);
                            }else if(data.message < 0){
                                $(el).css('color', '#c2c2c2');
                                var praiseNum = $(el).children('span').text();
                                --praiseNum;
                                if(praiseNum == 0) praiseNum = '';
                                $(el).children('span').text(praiseNum);
                            }
                        }else{
                            layer.msg("点赞失败", {time: 2000});
                        }
                    },
                    error: function(err) {
                        layer.msg("回调函数失败");
                    }
                });
            })

            /*显示与隐藏删除功能*/
            el.parents('.comment_item').hover(function() {
                el.parent().children('.del').show();
            }, function() {
                el.parent().children('.del').hide();
            });
        })
    }

    /**
     * 回复点赞
     */
    function praiseReplyFun() {
        $('.reply_praise').each(function (index) {
            var el = $(this);
            $(this).on('click', function() {
                var replyId = $(this).parents('.reply_item').children('li:first-child').children('input').val();
                $.ajax({
                    url: '/user/article/reply/praise',
                    type: 'POST',
                    data:{
                        'reply_id': replyId
                    },
                    success: function(data) {
                        data = JSON.parse(data);
                        console.log(data.message);
                        if(data.code=='200'){
                            if(data.message > 0){
                                $(el).css('color', '#369');
                                var praiseNum = $(el).children('span').text();
                                if(praiseNum == '' || praiseNum == null) praiseNum = 0;
                                $(el).children('span').text(++praiseNum);
                            }else if(data.message < 0){
                                $(el).css('color', '#c2c2c2');
                                var praiseNum = $(el).children('span').text();
                                --praiseNum;
                                if(praiseNum == 0) praiseNum = '';
                                $(el).children('span').text(praiseNum);
                            }
                        }else{
                            layer.msg("点赞失败", {time: 2000});
                        }
                    },
                    error: function(err) {
                        layer.msg("回调函数失败");
                    }
                });
            })

            /*显示与隐藏删除功能*/
            el.parents('.reply_item').hover(function() {
                el.parent().children('.reply_del').show();
            }, function() {
                el.parent().children('.reply_del').hide();
            });
        })
    }
})


/*将时间毫秒数转换为文字说明*/
function getDateDiff(dateTimeStamp){
    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var halfAMonth = day * 15;
    var month = day * 30;
    var year = month * 12;
    var now = new Date().getTime();
    var diffValue = now - dateTimeStamp;
    if(diffValue < 0){return;}
    var yearC = diffValue / year;
    var monthC = diffValue / month;
    var halfAMonthC = diffValue / halfAMonth;
    var weekC = diffValue / (7*day);
    var dayC = diffValue / day;
    var hourC = diffValue / hour;
    var minC = diffValue / minute;
    var result = '';
    if(yearC>=1){
        result = "" + parseInt(yearC) + "年前";
    }
    else if(monthC>=1){
        result="" + parseInt(monthC) + "月前";
    }
    else if(halfAMonthC>=1){
        result="" + parseInt(halfAMonthC) + "月前";
    }
    else if(weekC>=1){
        result="" + parseInt(weekC) + "周前";
    }
    else if(dayC>=1){
        result=""+ parseInt(dayC) +"天前";
    }
    else if(hourC>=1){
        result=""+ parseInt(hourC) +"小时前";
    }
    else if(minC>=1){
        result=""+ parseInt(minC) +"分钟前";
    }else
        result="刚刚";
    return result;
}
